import { resolve } from 'path';
import * as fs from 'fs';
import { pathToFileURL } from 'url'


// 获取指定path下所有的文件
export function getFilesByDirPath(path: string) {
    return fs.readdirSync(path).filter(function (file) {
        return fs.statSync(resolve(path, file));
    });
};

export function traverseSourceDir(dir: string) {
    // 资源文件夹路径
    const path = resolve(process.cwd(), dir);
    const result: string[][] = [];
    // 获取每个文件夹下的文件
    const getDirectoriesResult = (path: string) => {
        const list = getFilesByDirPath(path);
        list.map(async (d) => {
            // 可能为file/dir,所以这里进行判断
            if (fs.statSync(resolve(path, d)).isDirectory()) {
                // 文件夹，递归检索文件夹
                getDirectoriesResult(resolve(path, d));
            } else {
                result.push([path, d]);
            }
        });
    };
    getDirectoriesResult(path);
    return result;
};

/* 根据路径获取API名 */
export function get_api_name(path: string, fileName?: string) {
    const file_name = fileName ? fileName : process.env.FILENAME
    const file_url = pathToFileURL(path).href.split(`/${file_name}`)[0]
    const file_url_1 = file_url.split(process.env.APIINPUT + "/")[1]
    return file_url_1 ? file_url_1.replaceAll("/", ".") : ''
}


/**
 *
 * 获取文件夹下所有符合条件的文件
 * @param {string} dirw
 * @param {string} fileName 
 * @param {string} inputUrl
 */
export function get_file_link(dir: string) {
    const all_link = traverseSourceDir(dir)
    let obj: Record<string, string> = {}
    all_link.forEach(item => {
        if (item[1] === process.env.FILENAME) {
            const name = get_api_name(item[0])
            // 默认指定文件所在位置为接口
            name && (obj[name as string] = `${item[0]}${process.env.SPLITSTR}${process.env.FILENAME}`)
        }
    })
    return obj
}
/**
 *
 * 转化config文件common为esbuild,rollup可编译对象
 */
export function get_common(common: string[]) {
    let common_obj: Record<string, string> = {}
    common.forEach(item => {
        common_obj[`global.common["${item}"]`] = `require('${item}')`
    });
    return common_obj
}